#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import abort, g
from flask_restful import Resource, reqparse, marshal_with, fields

from src.api import api, meta_fields
from src.api.auth import self_only
from src.models.category import Category
from src.helpers import paginate
from src.extensions import auth


category_parser = reqparse.RequestParser()
category_parser.add_argument('name', type=unicode, required=True)
category_parser.add_argument('description', type=unicode, required=True)

category_collection_parser = reqparse.RequestParser()
category_collection_parser.add_argument('name', type=unicode, required=False)
category_collection_parser.add_argument('description', type=unicode, required=False)


# Marshaled field definitions for task objects
category_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'description': fields.String
}

# Marshaled field definitions for collections of task objects
category_collection_fields = {
    'items': fields.List(fields.Nested(category_fields)),
    'meta': fields.Nested(meta_fields),
}


class CategoryResource(Resource):
    @marshal_with(category_fields)
    def get(self, category_id=None):
        category = Category.get_by_id(category_id)

        if not category:
            abort(404)

        return category

    @auth.login_required
    @marshal_with(category_fields)
    def post(self, category_id=None):
        update_category = Category.get_by_id(category_id)
        category = Category.update(update_category, **category_parser.parse_args())
        return category

    @auth.login_required
    @self_only
    def delete(self, category_id=None):
        update_category = Category.get_by_id(category_id)
        Category.delete(update_category)
        return 204


class CategoryCollectionResource(Resource):

    @marshal_with(category_collection_fields)
    @paginate()
    def get(self):
        # Get the user's categorys
        categorys = Category.query

        args = category_collection_parser.parse_args()
        # fancy url argument query filtering!
        if args['name'] is not None:
            categorys.filter_by(title=args['name'])

        return categorys

    @auth.login_required
    @marshal_with(category_fields)
    def post(self):
        args = category_parser.parse_args()
        # user owns the task
        category = Category.create(**args)
        return category, 201


api.add_resource(CategoryResource, '/category/<int:category_id>')  # category 删改查
api.add_resource(CategoryCollectionResource, '/category')  # category 分页差，增
